package org.lqq.serverRegisterAndFinder.serverRegister.etcd;

import mousio.etcd4j.EtcdClient;
import mousio.etcd4j.promises.EtcdResponsePromise;
import mousio.etcd4j.requests.EtcdKeyGetRequest;
import mousio.etcd4j.responses.EtcdKeysResponse;
import org.lqq.serverRegisterAndFinder.etcd.EtcGuideThread;
import org.lqq.serverRegisterAndFinder.etcd.EtcdConst;
import org.lqq.serverRegisterAndFinder.etcd.EtcdRefreshThread;
import org.lqq.serverRegisterAndFinder.serverRegister.ServerRegister;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by 李清泉 on 2017/11/2.
 *
 * @remark
 */
public class EtcdServerRegister implements ServerRegister{


    private EtcdClient etcdClient;


    public EtcdServerRegister(EtcdClient etcdClient){
        this.etcdClient=etcdClient;
    }
    @Override
    public void registerToServer(String serverName,String address) {
        try {
            new  Thread(new EtcdRefreshThread(etcdClient,serverName,address)).start();//启动一个线程监听数据变化

            EtcdResponsePromise<EtcdKeysResponse>   p=etcdClient.putDir(EtcdConst.etcdKey+"/"+EtcdConst.sysKey+"/"+serverName+"-"+address).ttl(60).send();
           // p.get(); // 加上这个get()用来保证设置完成，走下一步，get会阻塞，由上面client的retry策略决定阻塞的方式
            new Thread(new EtcGuideThread(etcdClient,serverName,address)).start(); // 启动一个守护线程来定时刷新节点
        } catch (Exception e) {
            // TODO: handle exception
           e.printStackTrace();
        }
    }

    private String createVal(String address, String preValue) {
        Set<String> set=new HashSet<>();
        if(preValue!=null&&preValue.trim()!=""){
            String[] preVArr=preValue.split(",");
            for(String s:preVArr){
                if(s!=null&&s.trim().length()>0) {
                    set.add(s.trim());
                }
            }
        }
        set.add(address.trim());
        String val="";
        for(String s:set){
            val+=s+",";
        }
        if(val.length()>0){
            val=val.substring(0,val.length()-1);
        }
        return val;
    }
}
